package com.zyx.mpsimple.dao.base;

import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyx.mpsimple.mapper.FruitMapper;
import com.zyx.mpsimple.pojo.Fruit;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author Yaxi.Zhang
 * @since 2022/7/4 09:45
 */
public class BaseDAO {

    public static SqlSession session;

    static {
        // 获取配置文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mp.cfg.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        MybatisSqlSessionFactoryBuilder mybatisSessionFactoryBuilder = new MybatisSqlSessionFactoryBuilder();

        // 通过配置文件获取session工厂
        SqlSessionFactory sessionFactory = mybatisSessionFactoryBuilder.build(inputStream);

        // 获取一个session会话，true表示自动提交，可以不传参，默认为false
        session = sessionFactory.openSession(true);
    }


    public static <T> T getMapper(Class<T> clazz) {
        return session.getMapper(clazz);
    }

    public static void main(String[] args) {
        FruitMapper mapper = BaseDAO.getMapper(FruitMapper.class);

        Fruit fruit = mapper.selectById(3);
        System.out.println(fruit);
    }
}
